package cn.ichiva.dl4j.gnn.common;

import javax.swing.*;
import java.awt.*;
import java.util.LinkedHashMap;

public class Console extends LinkedHashMap<String,String> {

    private JFrame frame = new JFrame();

    public Console(String title) {
        frame.setTitle(title);
        frame.setSize(800,600);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setLayout(new GridLayout(10,1,10,10));
    }

    @Override
    public String put(String key, String value) {
        String res = super.put(key, value);

        for (Component component : frame.getRootPane().getContentPane().getComponents()) {
            frame.remove(component);
        }

        forEach((k,v)->{
            JPanel panel = new JPanel();
            panel.setLayout(new FlowLayout((FlowLayout.LEFT)));
            panel.add(new KeyLabel(k));
            panel.add(new ValLabel(v));
            frame.add(panel);
        });

        frame.invalidate();
        frame.validate();
        return res;
    }

    public Console() {
        this("DL4J Console");
    }

    public void show(){
        frame.setVisible(true);
    }

    public static void main(String[] args) throws InterruptedException {
        Console console = new Console();
        console.put("min = ","42");
        console.put("max = ","1354");
        console.put("avg = ","786");
        console.show();

        while (true){
            Thread.sleep(1000);
            console.put("now = ","" + Math.random());
        }
    }

    private class KeyLabel extends JLabel {
        public KeyLabel(String k) {
            super(k);
            setFont(new Font("黑体",Font.BOLD,24));
        }
    }

    private class ValLabel extends JLabel {
        public ValLabel(String k) {
            super(k);
            setFont(new Font("黑体",Font.PLAIN,24));
            setForeground(Color.RED);
        }
    }
}
